package com.serkol.utils;

import com.serkol.ams.AmsApplication;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Objects;

@Log4j2
public class LoadFont {
    public static Font loadFont(float fontSize) throws IOException, FontFormatException  //第一个参数是外部字体名，第二个是字体大小
    {


        final String fontFile = "/font/sans.ttf";
        final String fontFamily = "宋体";
        GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
       // System.out.println(graphicsEnvironment.);
        String[] fontFamilies = graphicsEnvironment.getAvailableFontFamilyNames();
/*
        for (String eachFamily : fontFamilies) {
            if (fontFamily.equals(eachFamily)) {
                System.out.println(fontFamily);
                log.info("Font in env, return");
                return new Font(fontFamily, Font.BOLD, (int) Math.ceil(fontSize));
            }
        }*/

        Font font;
        if (isInJar()) {
            log.debug("Running in JAR mode, try load resource TTC");
            font = Font.createFont(Font.TRUETYPE_FONT,
                    Objects.requireNonNull(AmsApplication.class.getClassLoader().getResourceAsStream(fontFile)));
        } else {
            log.debug("Running in local mode, try load classpath TTC");
            font = Font.createFont(Font.TRUETYPE_FONT,
                    new File(ResourceUtils.getURL("classpath:").getPath(), fontFile));
        }

        font = font.deriveFont(Font.TRUETYPE_FONT, fontSize);
        log.info("Register font family {}", font.getFontName());
        graphicsEnvironment.registerFont(font);
        return font;

    }

    /**
     * 判断当前是否为 JAR 方式启动
     *
     * @return 当为 true 时为 JAR 方式启动，否则为非 JAR
     */
    private static boolean isInJar() {
        try {
            Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources("");
            if (resources.hasMoreElements()) {
                log.debug("Application is in JAR!");
                return StringUtils.equalsIgnoreCase(resources.nextElement().getProtocol(), "jar");
            }
        } catch (IOException e) {
            log.error("Failed load resource, ", e);
            throw new RuntimeException(e);
        }
        log.debug("Application is not in JAR!");
        return false;
    }
}